package com.hougong.im;

import com.hougong.im.transport.BaseFrame;
import com.hougong.im.utils.SpringContextUtils;
import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 事件分发
 */
public class Dispather {
    private static final Logger LOGGER=LoggerFactory.getLogger(Dispather.class);
    //项目启动的时候应该把这个键值对 "messageType"=>"classs.method";
    private static Map<Short,String> requestHandlerMap =new LinkedHashMap<>();

    public static Map<Short, String> getRequestHandlerMap() {
        return requestHandlerMap;
    }

    public static void setRequestHandlerMap(Map<Short, String> requestHandlerMap) {
        Dispather.requestHandlerMap = requestHandlerMap;
    }

    public  static void handler(BaseFrame baseFrame, Channel channel) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        if(baseFrame!=null){
            String beanMethod = requestHandlerMap.get(baseFrame.getBizType());
            String[] split = beanMethod.split("#");
            Object obj=SpringContextUtils.getBean(split[0]);
            Method method = obj.getClass().getMethod(split[1], BaseFrame.class, Channel.class);
            method.invoke(obj,baseFrame,channel);
        }else {
            LOGGER.info("baseframe 消息为null  ");
        }
    }
}
